import tkinter as tk
import requests
from bs4 import BeautifulSoup
import pyperclip
import pystray
from pystray import MenuItem as item
from PIL import Image, ImageDraw
import json
import os

# 定义文件路径
config_file = "config.json"

# 读取配置文件
def load_config():
    if os.path.exists(config_file):
        with open(config_file, 'r', encoding='utf-8') as file:
            config = json.load(file)
            return config
    return {}

# 保存配置到文件
def save_config():
    config = {
        "base_url": entry1.get(),
        "endpoint": entry2.get(),
        "request_type": entry3.get(),
        "link_text": entry4.get(),
        "div_id": entry5.get()
    }
    with open(config_file, 'w', encoding='utf-8') as file:
        json.dump(config, file, ensure_ascii=False, indent=4)

# 定义关闭按钮最小化到托盘的功能
def on_quit(icon, item):
    save_config()  # 保存配置
    icon.stop()

def on_minimize_to_tray():
    image = Image.new('RGBA', (64, 64), (255, 255, 255, 0))
    draw = ImageDraw.Draw(image)
    draw.rectangle([0, 0, 64, 64], fill=(255, 255, 255))

    icon = pystray.Icon("name", image, "API 请求工具", menu=pystray.Menu(
        item('显示窗口', on_show_window),
        item('下一步', on_next_step),
        item('退出', on_quit)
    ))
    icon.run_detached()

    root.withdraw()
    icon.visible = True

def on_show_window(icon, item):
    root.deiconify()
    icon.visible = False

def on_next_step(icon, item):
    send_request()

def send_request():
    base_url = entry1.get()  # 请求地址
    endpoint = entry2.get()  # 接口名
    request_type = entry3.get().upper()  # 请求类型 (get 或 post)
    div_id = entry5.get()  # 获取要提取的 div 的 id
    link_text = entry4.get()  # 获取 a 标签显示的内容

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    url = f"{base_url}/{endpoint}"
    
    try:
        if request_type == "GET":
            response = requests.get(url, headers=headers)
        elif request_type == "POST":
            response = requests.post(url, headers=headers)
        else:
            result_label.config(text="不支持的请求类型！")
            return
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            content = soup.find('div', id=div_id)
            if content:
                content_text = content.get_text(strip=True)
                pyperclip.copy(content_text)
            else:
                result_label.config(text=f"未找到指定的 div (id={div_id}) 元素！")
            
            link = soup.find('a', id=link_text)
            if link and link.get('href'):
                new_link = link.get('href')
                entry2.delete(0, tk.END)
                entry2.insert(0, new_link)
                result_label.config(text=f"链接已替换为: {link['href']}")
            else:
                result_label.config(text=f"未找到指定的 a 标签，或该标签没有 href 属性！")
        else:
            result_label.config(text=f"请求失败，状态码: {response.status_code}")
    
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        result_label.config(text=f"请求失败: {e}")

def toggle_more():
    if entry3.winfo_ismapped() and entry4.winfo_ismapped() and entry5.winfo_ismapped():
        entry3.pack_forget()
        entry4.pack_forget()
        entry5.pack_forget()
        label3.pack_forget()
        label4.pack_forget()
        label5.pack_forget()
        more_button.config(text="更多")
    else:
        label3.pack(anchor="w", padx=5, pady=5)
        entry3.pack(fill=tk.X, padx=5, pady=5)
        label4.pack(anchor="w", padx=5, pady=5)
        entry4.pack(fill=tk.X, padx=5, pady=5)
        label5.pack(anchor="w", padx=5, pady=5)
        entry5.pack(fill=tk.X, padx=5, pady=5)
        more_button.config(text="收起")

# 创建主窗口
root = tk.Tk()
root.title("API测试工具")
# root.geometry("300x260")

# 加载配置文件中的内容
config = load_config()

label1 = tk.Label(root, text="请求地址:")
label1.pack(anchor="w", padx=5, pady=5)
entry1 = tk.Entry(root, width=30)
entry1.insert(0, config.get("base_url", ""))  # 填充保存的内容
entry1.pack(fill=tk.X, padx=5, pady=5)

label2 = tk.Label(root, text="接口名:")
label2.pack(anchor="w", padx=5, pady=5)
entry2 = tk.Entry(root, width=30)
entry2.insert(0, config.get("endpoint", ""))  # 填充保存的内容
entry2.pack(fill=tk.X, padx=5, pady=5)

label3 = tk.Label(root, text="请求类型:")
label3.pack_forget()
entry3 = tk.Entry(root, width=30)
entry3.insert(0, config.get("request_type", "GET"))  # 填充保存的内容
entry3.pack_forget()

save_button = tk.Button(root, text="确认", command=send_request)
save_button.pack(pady=20)

more_button = tk.Button(root, text="更多", command=toggle_more)
more_button.pack(pady=10)

label4 = tk.Label(root, text="a标签id:")
label4.pack_forget()
entry4 = tk.Entry(root, width=30)
entry4.insert(0, config.get("link_text", "next_url"))  # 填充保存的内容
entry4.pack_forget()

label5 = tk.Label(root, text="div内容id:")
label5.pack_forget()
entry5 = tk.Entry(root, width=30)
entry5.insert(0, config.get("div_id", "content"))  # 填充保存的内容
entry5.pack_forget()


result_label = tk.Label(root, text="", justify=tk.LEFT)
result_label.pack(pady=10)

# 在窗口关闭时最小化到托盘
root.protocol("WM_DELETE_WINDOW", on_minimize_to_tray)

root.mainloop()
